/*******************************************************************************
 * Copyright (c) 2012, 2013 XML-Print Project.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     XML-Print Project - initial API and implementation
 ******************************************************************************/
package info.xmlprint.core.referencesystem;

import java.io.Serializable;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;

/*
 * Base data model for ReferenceFile and Reference System
 */
public abstract class AbstractBaseItem implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1019014891744537301L;
	
	protected Map<String, String> valueMap;
	// Mapping zwischen xml-element-name und Field-attribute-name
	protected Map<String, String> nodeNameMap;
	protected AbstractBaseGroup group;
	protected String rootElementName;

	public AbstractBaseItem() {
		init();
		setRootElementName();
	}

	public AbstractBaseGroup getGroup() {
		return group;
	}

	public String getValueOf(String key) {
		String s = valueMap.get(key);
		if (s == null)
			s = "";
		return s;
	}

	public abstract void init();

//	void nodeAddChildren(Element parent, String[] attrNames) {
//		for (String name : attrNames) {
//			parent.addElement(nodeNameMap.get(name)).setText(getValue(name));
//		}
//	}

	protected void readNodeValue(Node parentNode, String[] keyNames) {
		if(parentNode==null){
			return;
		}
		String nodeName;
		for (String key : keyNames) {
			nodeName = nodeNameMap.get(key);
			if (nodeName == null)
				continue;

			Node node = parentNode.selectSingleNode(nodeNameMap.get(key));
			if (node != null) {
				setValueOf(key, node.getText());
			}
		}
	}

	public void setGroup(AbstractBaseGroup group) {
		this.group = group;
	}

	public abstract void setRootElementName();

	/*
	 * ReferenceField nach xmlDocument transformieren
	 */
//	public abstract Document getXmlDocument();

	public void setValueOf(String name, String value) {
		valueMap.put(name, value);
	}

	/*
	 * 
	 */
	public void updateByDoc(Document doc) {
		if (doc == null) {
			return;
		}

		Element root = doc.getRootElement();
		updateByElement(root);
	}

	public abstract void updateByElement(Element elem);
}
